// 定义和用户当前体重相关的接口
const Router = require('koa-router')
const router = new Router()
const {
    changeNowWeight,
    getWeightData,
} = require('../controllers/index.js')
const { verify } = require('../utils/jwt.js')


router.prefix('/weight')

// 修改用户当前体重
router.post('/changeNowWeight', verify(), async (ctx, next) => {
    const user_id = ctx.user_id
    const { nowWeight, time } = ctx.request.body
    const res = await changeNowWeight(user_id, nowWeight, time)
    // console.log(res);
    try {
        if (res.affectedRows) {
            if (res.affectedRows) {
                ctx.body = {
                    code: 200,
                    msg: '修改成功',
                }
            } else {
                ctx.body = {
                    code: 200,
                    msg: '修改失败',
                }
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }
})

// 获取用户最近七天的体重数据
router.get('/getWeightData', verify(), async (ctx, next) => {
    const user_id = ctx.user_id
    const { time } = ctx.query
    const res = await getWeightData(user_id, time)
    // console.log(res);
    try {
        if (res.length) {
            ctx.body = {
                code: 200,
                data: res,
                msg: '获取成功',
            }
        } else {
            ctx.body = {
                code: 200,
                data: [],
                msg: '暂无数据',
            }
        }
    } catch (error) {
        ctx.body = {
            code: 500,
            data: error,
            msg: '服务器异常',
        }
    }
})

module.exports = {
    weightRouter: router
}